package org.chabad.android;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.*;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Zmanim extends Activity {
	private WebView 	_WebView;
	private int			_CurrentUrlResId = R.string.zmanim_url;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Context ctx = this;
       
        Intent intent = getIntent();
        if(intent != null)
        {
        	_CurrentUrlResId = intent.getIntExtra("org.chabad.android.UrlId", R.string.zmanim_url);
        }
        _WebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = _WebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        _WebView.setWebViewClient(new WebViewClient() {
        	   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        	     Toast.makeText(ctx, "Oh no! " + description, Toast.LENGTH_SHORT).show();
        	   }
        	   @Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url) {
        		// TODO Auto-generated method stub
        		if(url.startsWith(getString(R.string.safe_url_prefix)))
        		{
        			return false;
        		}
        		Intent myIntent = new Intent(Intent.ACTION_VIEW,
        				Uri.parse(url));
        		startActivity(myIntent); 
        		return true;
        	}
        	 });

		RefreshWebView(ctx, _CurrentUrlResId);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = this.getMenuInflater();
        inflater.inflate(R.menu.generic, menu);
        return true;
    }
    
    @Override
    public final boolean onOptionsItemSelected(final MenuItem item) {
        final Context ctx = this;
        switch (item.getItemId()) {
            case R.id.menu_refresh:
                RefreshWebView( ctx, _CurrentUrlResId );
            	return true;
            case R.id.menu_locate:
            	_CurrentUrlResId = R.string.locate_url;
                RefreshWebView( ctx, _CurrentUrlResId );
            	return true;
            case R.id.menu_zmanim:
            	_CurrentUrlResId = R.string.zmanim_url;
                RefreshWebView( ctx, _CurrentUrlResId );
            	return true;
            case R.id.menu_home:
            	_CurrentUrlResId = R.string.home_url;
                RefreshWebView( ctx, _CurrentUrlResId );
            	return true;
            case R.id.menu_prefrences:
		    	Intent i = new Intent();
		    	i.setClassName("org.chabad.android","org.chabad.android.Prefrences");
		    	startActivity(i);
            	return true;
            default:
                return false;
        }
    }
    
    public void RefreshWebView(Context ctx, int urlResId)
    {
        String zip = null;
        String serviceName = "Prefrences";
        List<Address> addresses = null;
        SharedPreferences prefs = getSharedPreferences("Chabad.org", MODE_PRIVATE);

        zip = prefs.getString("ZipOverride", null);
        
        if(zip == null)
        {
	        LocationManager locService = (LocationManager)getSystemService(LOCATION_SERVICE);
	        Location loc = locService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
	        serviceName = "GPS";
	        if(loc == null)
	        {
	        	loc = locService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	        	serviceName = "Network";
	        }
	        if(loc != null)
	        {
		        Geocoder geocoder = new Geocoder(ctx);
				try {
					addresses = geocoder.getFromLocation(loc.getLatitude() , loc.getLongitude(), 1);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        if (addresses != null && addresses.size() > 0) {
		            Address address = addresses.get(0);
		            zip =  address.getPostalCode();
		        }
		        Toast.makeText(ctx, "Zip("+ serviceName +"): " + zip, Toast.LENGTH_SHORT).show();
	        }else{
		        Toast.makeText(ctx, "No GPS or network available", Toast.LENGTH_SHORT).show();		        	
	        }
        }
		_WebView.loadUrl(getString( urlResId, zip));
    }

}